export default {
  namespaced: true,
  state: {
    carts: uni.getStorageSync('carts') || [],
    msg: '我是购物车'
  },
  getters: {
    cartCount(state) {
      return state.carts.length;
    },
    allChecked(state) {
      return state.carts.every((item) => item.goods_state);
    },
    checkdCount(state) {
      // 勾选上的 goods_number 相加
      return state.carts.reduce((sum, item) => {
        if (!item.goods_state) return sum;
        return (sum += item.goods_number);
      }, 0);
    },
    amount(state) {
      return state.carts.reduce((amount, item) => {
        // 如果商品非选中的则不参与计算
        if (!item.goods_state) return amount;
        // 金额 = 单价 * 数量
        return (amount += item.goods_number * item.goods_price);
      }, 0);
    }
  },
  mutations: {
    addToCart(state, goods) {
      // 将goods 加入到carts当中
      // goods如果在carts中不存在直接push  如果存在 数量+1
      const result = state.carts.find((item) => item.goods_id === goods.goods_id);
      console.log(goods);
      if (result) {
        result.goods_number += 1;
      } else {
        state.carts.push(goods);
      }
      // 存入本地
      this.commit('m_cart/saveToStorage');
    },
    saveToStorage(state) {
      uni.setStorageSync('carts', state.carts);
    },
    // 修改选中状态
    toggleState(state, index) {
      state.carts[index].goods_state = !state.carts[index].goods_state;
      // 存储到本地
      this.commit('m_cart/saveToStorage');
    },
    // 修改全选
    toggleAll(state, allChecked) {
      // 全选
      state.carts.forEach((item) => (item.goods_state = !allChecked));
      // 存储到本地
      this.commit('m_cart/saveToStorage');
    },
    // 加商品
    increaseCount(state, index) {
      state.carts[index].goods_number += 1;
      // 存储到本地
      this.commit('m_cart/saveToStorage');
    },
    // 减商品
    decreaseCount(state, index) {
      if (state.carts[index].goods_number <= 1) return;
      state.carts[index].goods_number -= 1;
      // 存储到本地
      this.commit('m_cart/saveToStorage');
    },
    // 更新购物车
    updateCart(state, goods) {
      state.carts = goods;
      // 存储到本地
      this.commit('m_cart/saveToStorage');
    }
  }
};
